import React from 'react'
import { Card, Col, DatePicker, message, Radio, Row } from 'antd'
import { Axis, Chart, Geom, Legend, Tooltip } from 'bizcharts'
import img1 from '../../assets/merchant/img1.png'
import img2 from '../../assets/merchant/img2.png'
import img3 from '../../assets/merchant/img3.png'
import img4 from '../../assets/merchant/img4.png'
import img5 from '../../assets/merchant/img5.png'
import img6 from '../../assets/merchant/img6.png'
import img7 from '../../assets/merchant/img7.png'
import img8 from '../../assets/merchant/img8.png'
import Styles from './Dashboard.less'
import { fetchPost } from '../../utils/request'
import { getTimeDistance } from '../../utils/DateUtils'

const {RangePicker} = DatePicker

class Dashboard extends React.Component {
  constructor (props, context) {
    super(props, context)
    this.state = {
      fundCode: window.atob(this.props.location.query.fundCode),
      approvalRateRangePickerValue: getTimeDistance('month'),
      repayDataRangePickerValue: getTimeDistance('month'),
      isNewUser: '1',
      repayDataIsNewUser: '1',
      blocksData: {},
      approvalData: {},
      repayData: {},
    }
  }

  componentWillReceiveProps (nextProps, nextContext) {
    if (this.props !== nextProps) {
      this.setState({
        fundCode: window.atob(nextProps.location.query.fundCode)
      }, () => this.getAllData())
    }
  }

  componentDidMount () {
    this.getAllData()
  }

  getAllData () {
    this.getBlocksData()
    this.getApprovalData()
    this.getRepayData()
  }

  /**
   * 获取方块数据
   */
  getBlocksData () {
    fetchPost('/merchant/operational/stats', {'fundCode': this.state.fundCode}).then(json => {
      if (json.code === 0) {
        this.setState({
          blocksData: json.data
        })
      } else {
        message.error(json.msg)
      }
    })
  }

  /**
   * 获取申请数据
   */
  getApprovalData () {
    let startCreateDate = this.state.approvalRateRangePickerValue[0].format('YYYY-MM-DD')
    let endCreateDate = this.state.approvalRateRangePickerValue[1].format('YYYY-MM-DD')
    let isNewUser = this.state.isNewUser
    fetchPost('/merchant/operational/approval', {startCreateDate, endCreateDate, isNewUser}).then(json => {
      if (json.code === 0) {
        this.setState({
          approvalData: json.data
        })
      } else {
        message.error(json.msg)
      }
    })
  }

  /**
   * 获取还款数据
   */
  getRepayData () {
    let startRepaymentDate = this.state.repayDataRangePickerValue[0].format('YYYY-MM-DD')
    let endRepaymentDate = this.state.repayDataRangePickerValue[1].format('YYYY-MM-DD')
    let isNewUser = this.state.repayDataIsNewUser
    let fundCode = this.state.fundCode
    fetchPost('/merchant/operational/repay', {startRepaymentDate, endRepaymentDate, isNewUser, fundCode}).then(json => {
      if (json.code === 0) {
        this.setState({
          repayData: json.data
        })
      } else {
        message.error(json.msg)
      }
    })
  }

  /**
   * 筛选申请日期
   */
  selectApprovalRateDate (type) {
    let timeDistance = getTimeDistance(type)
    this.setState({
      approvalRateRangePickerValue: timeDistance,
    }, () => this.getApprovalData())
  }

  /**
   * 申请日期变化
   */
  handleApprovalRateRangePickerChange = (approvalRateRangePickerValue) => {
    this.setState({
      approvalRateRangePickerValue,
    }, () => this.getApprovalData())
  }

  /**
   * 筛选还款通过日期
   */
  selectRepayDate (type) {
    let timeDistance = getTimeDistance(type)
    console.log(type, timeDistance)
    this.setState({
      repayDataRangePickerValue: timeDistance,
    }, () => this.getRepayData())
  }

  /**
   * 还款日期变化
   */
  handleRepayRangePickerChange = (repayDataRangePickerValue) => {
    this.setState({
      repayDataRangePickerValue,
    }, () => this.getRepayData())
  }

  /**
   * 用户类型选择
   */
  isNewUserChange (e) {
    this.setState({
      isNewUser: e.target.value
    }, () => this.getApprovalData())
  }

  /**
   * 还款图表 用户类型选择
   */
  isRepayDataNewUserChange (e) {
    this.setState({
      repayDataIsNewUser: e.target.value
    }, () => this.getRepayData())
  }

  /**
   * 高亮选择的日期
   */
  static isActive (type, rangePickerValue) {
    const value = getTimeDistance(type)
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return ''
    }
    if (
      rangePickerValue[0].isSame(value[0], 'day') &&
      rangePickerValue[1].isSame(value[1], 'day')
    ) {
      return Styles.currentDate
    }
    return ''
  }

  render () {
    console.log('render')
    const cols = {
      month: {
        range: [0, 1]
      }
    }
    return (
      <div>
        {/*欢迎*/}
        {/*<div className={Styles.header}>*/}
        {/*  <h1>WelCome {this.state.blocksData.fundName}</h1>*/}
        {/*</div>*/}
        {/*数据方块*/}
        <div>
          <Row gutter={24}>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img3}/>
                </div>
                <div className={Styles.number}>
                  <span>Sum Capital(₹)</span>
                  <h1>{this.state.blocksData.sumCapital !== null ? this.state.blocksData.sumCapital : '-'}</h1>
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img7}/>
                </div>
                <div className={Styles.number}>
                  <span>Account Balance(₹)</span>
                  <h1>{this.state.blocksData.accountBalance !== null ? this.state.blocksData.accountBalance : '-'}</h1>
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img6}/>
                </div>
                <div className={Styles.number}>
                  <span>Money in the Loan(₹)</span>
                  <h1>{this.state.blocksData.moneyInTheLoan !== null ? this.state.blocksData.moneyInTheLoan : '-'}</h1>
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img4}/>
                </div>
                <div className={Styles.number}>
                  <span>Estimated GMV(Tomorrow)</span>
                  <h1>{this.state.blocksData.estimatedGMV !== null ? this.state.blocksData.estimatedGMV : '-'}</h1>
                </div>
              </Card>
            </Col>
          </Row>
          <Row gutter={24} style={{marginTop: 20}}>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img2}/>
                </div>
                <div className={Styles.number}>
                  <span>Loan Users</span>
                  <h1>{this.state.blocksData.loanUsers !== null ? this.state.blocksData.loanUsers : '-'}</h1>
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img5}/>
                </div>
                <div className={Styles.number}>
                  <span>Repeat Users</span>
                  <h1>{this.state.blocksData.repeatUsers !== null ? this.state.blocksData.repeatUsers : '-'}</h1>
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img1}/>
                </div>
                <div className={Styles.number}>
                  <span>Orders</span>
                  <h1>{this.state.blocksData.orders !== null ? this.state.blocksData.orders : '-'}</h1>
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={true}>
                <div className={Styles.logo}>
                  <img width='50px' height='50px' className={Styles.logo} src={img8}/>
                </div>
                <div className={Styles.number}>
                  <span>Revenue(₹)</span>
                  <h1>{this.state.blocksData.revenue !== null ? this.state.blocksData.revenue : '-'}</h1>
                </div>
              </Card>
            </Col>
          </Row>
        </div>
        {/*通过率图表*/}
        <div>
          <Card title='Approval Rate' style={{marginTop: 50}}
                extra={<Radio.Group defaultValue={this.state.isNewUser} onChange={(e) => this.isNewUserChange(e)}>
                  <Radio value='0'>Repeat User</Radio>
                  <Radio value='1'>New User</Radio>
                  <Radio value='2'>All</Radio>
                </Radio.Group>}>
            <div style={{float: 'left', width: '10%', marginTop: 100}}>
              <span>Average Rate</span>
              <h1>{this.state.approvalData.averageRate}</h1>
            </div>
            <div style={{marginLeft: 100, float: 'right'}}>
              <div className={Styles.salesExtra}>
                <a className={Dashboard.isActive('today', this.state.approvalRateRangePickerValue)}
                   onClick={() => this.selectApprovalRateDate('today')}>Today</a>
                <a className={Dashboard.isActive('week', this.state.approvalRateRangePickerValue)}
                   onClick={() => this.selectApprovalRateDate('week')}>Week</a>
                <a className={Dashboard.isActive('month', this.state.approvalRateRangePickerValue)}
                   onClick={() => this.selectApprovalRateDate('month')}>Month</a>
                <a className={Dashboard.isActive('year', this.state.approvalRateRangePickerValue)}
                   onClick={() => this.selectApprovalRateDate('year')}>Year</a>
              </div>
              <RangePicker
                value={this.state.approvalRateRangePickerValue}
                onChange={this.handleApprovalRateRangePickerChange}
                style={{width: 256}}
              />
            </div>
            <div style={{float: 'left', width: '90%'}}>
              <div>
                <div style={{marginLeft: 100, float: 'left'}}>
                  <span>Submitted Orders :</span>{this.state.approvalData.submittedOrders}
                  <span style={{marginLeft: 50}}>Approval Orders :</span>{this.state.approvalData.approvalOrders}
                </div>
              </div>
              <div style={{marginTop: 20}}>
                <Chart height={400} data={this.state.approvalData.approvalRateDetail} forceFit
                       placeholder={<div style={{position: 'relative', top: '48%', textAlign: 'center'}}>No Data</div>}>
                  <Legend/>
                  <Axis name="date"/>
                  <Axis name="dailyApprovalRate"/>
                  <Tooltip
                    crosshairs={{
                      type: 'y'
                    }}
                  />
                  <Geom
                    type="line"
                    position="date*dailyApprovalRate"
                    size={2}
                  />
                </Chart>
              </div>
            </div>
          </Card>
        </div>
        {/*还款数据*/}
        <div>
          <Card title='Repay Data' style={{marginTop: 50}}
                extra={<Radio.Group defaultValue={this.state.repayDataIsNewUser}
                                    onChange={(e) => this.isRepayDataNewUserChange(e)}>
                  <Radio value='0'>Repeat User</Radio>
                  <Radio value='1'>New User</Radio>
                  <Radio value='2'>All</Radio>
                </Radio.Group>}>
            <div style={{float: 'left', width: '10%', marginTop: 100}}>
              <div>
                <span>D0 Overdue Rate</span>
                <h1>{this.state.repayData.d0OverdueRate}</h1>
              </div>
              <div style={{marginTop: 50}}>
                <span>Overdue Rate</span>
                <h1>{this.state.repayData.overdueRate}</h1>
              </div>

            </div>
            <div style={{marginLeft: 100, float: 'right'}}>
              <div className={Styles.salesExtra}>
                <a className={Dashboard.isActive('today', this.state.repayDataRangePickerValue)}
                   onClick={() => this.selectRepayDate('today')}>Today</a>
                <a className={Dashboard.isActive('week', this.state.repayDataRangePickerValue)}
                   onClick={() => this.selectRepayDate('week')}>Week</a>
                <a className={Dashboard.isActive('month', this.state.repayDataRangePickerValue)}
                   onClick={() => this.selectRepayDate('month')}>Month</a>
                <a className={Dashboard.isActive('year', this.state.repayDataRangePickerValue)}
                   onClick={() => this.selectRepayDate('year')}>Year</a>
              </div>
              <RangePicker
                value={this.state.repayDataRangePickerValue}
                onChange={this.handleRepayRangePickerChange}
                style={{width: 256}}
              />
            </div>
            <div style={{float: 'left', width: '90%'}}>
              <div style={{marginTop: 20}}>
                <Chart height={400} data={this.state.repayData.repayDataDetail} scale={cols} forceFit
                       placeholder={<div style={{position: 'relative', top: '48%', textAlign: 'center'}}>No Data</div>}>
                  <Legend/>
                  <Axis name="date"/>
                  <Axis
                    name="rate"
                  />
                  <Tooltip
                    crosshairs={{
                      type: 'y'
                    }}
                  />
                  <Geom
                    type="line"
                    position="date*rate"
                    size={2}
                    color={'type'}
                    style={{
                      shadowColor: 'l (270) 0:rgba(21, 146, 255, 0)',
                      shadowBlur: 60,
                      shadowOffsetY: 6
                    }}
                  />
                </Chart>
              </div>
            </div>
          </Card>
        </div>
      </div>
    )
  }

}

export default Dashboard
